package com.clear.honghefinance.wechat.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析xml消息工具类
 */
public class XmlMessageParseUtil {

    public static Map<String, String> parseXml(InputStream is) {
        Map<String, String> map = new HashMap<>();
        try (  // 从request中获取输入流
               InputStream inputStream = is;
        ) {
            //获取xml解析工具类
            SAXReader saxReader = new SAXReader();
            // 读取request输⼊流，获得Document对象
            Document document = saxReader.read(inputStream);
            //获得xml root节点
            Element rootElement = document.getRootElement();
            // 获取root下所有子节点
            List<Element> elements = rootElement.elements();
            elements.stream().forEach(element -> {
                map.put(element.getName(), element.getStringValue());
            });
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}